package MyList;

import java.lang.reflect.Array;
import java.util.Arrays;

public class MyList implements Operations{
    public int[] arr;
    public int usedSize;

    public MyList() {
        arr = new int[10];
    }

    //判断数组是否满
    public boolean isFull() {
        return this.usedSize == arr.length;
    }

    @Override
    public void add(int data) {
        if (this.isFull()) {
            this.expansion();
        }

        arr[this.usedSize++] = data;
    }

    //扩容
    public void expansion() {
        arr = Arrays.copyOf(arr, arr.length * 2);
    }

    @Override
    public void add(int pos, int data) {
        if (pos < 0 || pos > this.usedSize) {
            throw new PosException("下标不合法");
        }

        if (pos == this.usedSize) {
            this.add(data);
            return;
        }

        if (this.isFull()) {
            this.expansion();
        }

        for (int i = this.usedSize - 1; i >= pos; i--) {
            arr[i + 1] = arr[i];
        }
        arr[pos] = data;
        this.usedSize++;
    }

    @Override
    public boolean contains(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if (arr[i] == toFind) {
                return true;
            }
        }

        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if (arr[i] == toFind) {
                return i;
            }
        }

        return -1;
    }

    @Override
    public int get(int pos) {
        if (pos < 0 || pos >= this.usedSize) {
            throw new PosException("下标不合法");
        }

        return arr[pos];
    }

    @Override
    public void set(int pos, int value) {
        if (pos < 0 || pos > this.usedSize) {
            throw new PosException("下标不合法");
        }

        if (pos == this.usedSize) {
            this.add(value);
            return;
        }

        this.arr[pos] = value;
    }

    @Override
    public void remove(int toRemove) {
        int index = 0;
        boolean isExist = false;

        for (int i = 0; i < this.usedSize; i++) {
            if (this.arr[i] == toRemove) {
                index = i;
                isExist = true;
                break;
            }
        }

        if (isExist) {
            for (int i = index; i < this.usedSize; i++) {
                this.arr[i] = arr[i + 1];
            }

            this.usedSize--;
        } else {
            System.out.println("该数不存在");
        }
    }

    @Override
    public int size() {
        return this.arr.length;
    }

    @Override
    public void clear() {
        this.usedSize = 0;
    }

    public void show() {
        for (int i = 0; i < this.usedSize; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }
}
